"""
库存管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

from app.models.inventory import Inventory, InventoryRecord, InventoryType
from app.models.product import Product, ProductVariant
from app.schemas.inventory import InventoryRecordSchema
from app.extensions import db
from app.utils.auth import admin_required

inventory_bp = Blueprint('inventory', __name__)

@inventory_bp.route('/records', methods=['GET'])
@jwt_required()
def get_inventory_records():
    """获取库存记录"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    
    query = InventoryRecord.query
    
    # 过滤条件
    record_type = request.args.get('type')
    if record_type:
        query = query.filter_by(type=record_type)
    
    product_id = request.args.get('product_id', type=int)
    if product_id:
        query = query.filter_by(product_id=product_id)
    
    variant_id = request.args.get('variant_id', type=int)
    if variant_id:
        query = query.filter_by(variant_id=variant_id)
    
    # 日期范围
    start_date = request.args.get('start_date')
    if start_date:
        query = query.filter(InventoryRecord.created_at >= datetime.fromisoformat(start_date))
    
    end_date = request.args.get('end_date')
    if end_date:
        query = query.filter(InventoryRecord.created_at <= datetime.fromisoformat(end_date))
    
    # 排序
    sort_by = request.args.get('sort_by', 'created_at')
    sort_order = request.args.get('sort_order', 'desc')
    
    if sort_order == 'desc':
        query = query.order_by(getattr(InventoryRecord, sort_by).desc())
    else:
        query = query.order_by(getattr(InventoryRecord, sort_by).asc())
    
    # 分页
    pagination = query.paginate(page=page, per_page=per_page)
    
    return jsonify({
        "records": InventoryRecordSchema(many=True).dump(pagination.items),
        "total": pagination.total,
        "pages": pagination.pages,
        "page": page,
        "per_page": per_page
    }), 200

@inventory_bp.route('/stock', methods=['GET'])
@jwt_required()
def get_current_stock():
    """获取当前库存"""
    product_id = request.args.get('product_id', type=int)
    variant_id = request.args.get('variant_id', type=int)
    
    if variant_id:
        variant = ProductVariant.query.get(variant_id)
        if not variant:
            return jsonify({"msg": "商品变体不存在"}), 404
        
        return jsonify({
            "product_id": variant.product_id,
            "variant_id": variant.id,
            "stock": variant.stock,
            "specifications": variant.specifications
        }), 200
    
    elif product_id:
        product = Product.query.get(product_id)
        if not product:
            return jsonify({"msg": "商品不存在"}), 404
        
        # 获取所有变体
        variants = ProductVariant.query.filter_by(product_id=product_id).all()
        
        return jsonify({
            "product_id": product.id,
            "product_name": product.name,
            "stock": product.stock,
            "variants": [
                {
                    "variant_id": v.id,
                    "specifications": v.specifications,
                    "stock": v.stock
                } for v in variants
            ]
        }), 200
    
    else:
        return jsonify({"msg": "请提供商品ID或变体ID"}), 400

@inventory_bp.route('/in', methods=['POST'])
@jwt_required()
@admin_required
def stock_in():
    """入库操作"""
    data = request.get_json()
    
    product_id = data.get('product_id')
    variant_id = data.get('variant_id')
    quantity = data.get('quantity')
    notes = data.get('notes', '')
    
    if not product_id or not quantity or quantity <= 0:
        return jsonify({"msg": "请提供有效的商品ID和入库数量"}), 400
    
    try:
        # 更新库存
        if variant_id:
            variant = ProductVariant.query.get(variant_id)
            if not variant:
                return jsonify({"msg": "商品变体不存在"}), 404
            
            variant.stock += quantity
            product = variant.product
        else:
            product = Product.query.get(product_id)
            if not product:
                return jsonify({"msg": "商品不存在"}), 404
            
            product.stock += quantity
        
        # 创建库存记录
        record = InventoryRecord(
            product_id=product_id,
            variant_id=variant_id,
            type=InventoryType.IN.value,
            quantity=quantity,
            notes=notes
        )
        
        db.session.add(record)
        db.session.commit()
        
        return jsonify({
            "msg": "入库成功",
            "record": InventoryRecordSchema().dump(record)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"入库操作失败: {str(e)}"}), 500

@inventory_bp.route('/out', methods=['POST'])
@jwt_required()
@admin_required
def stock_out():
    """出库操作"""
    data = request.get_json()
    
    product_id = data.get('product_id')
    variant_id = data.get('variant_id')
    quantity = data.get('quantity')
    notes = data.get('notes', '')
    
    if not product_id or not quantity or quantity <= 0:
        return jsonify({"msg": "请提供有效的商品ID和出库数量"}), 400
    
    try:
        # 更新库存
        if variant_id:
            variant = ProductVariant.query.get(variant_id)
            if not variant:
                return jsonify({"msg": "商品变体不存在"}), 404
            
            if variant.stock < quantity:
                return jsonify({"msg": "库存不足"}), 400
            
            variant.stock -= quantity
            product = variant.product
        else:
            product = Product.query.get(product_id)
            if not product:
                return jsonify({"msg": "商品不存在"}), 404
            
            if product.stock < quantity:
                return jsonify({"msg": "库存不足"}), 400
            
            product.stock -= quantity
        
        # 创建库存记录
        record = InventoryRecord(
            product_id=product_id,
            variant_id=variant_id,
            type=InventoryType.OUT.value,
            quantity=quantity,
            notes=notes
        )
        
        db.session.add(record)
        db.session.commit()
        
        return jsonify({
            "msg": "出库成功",
            "record": InventoryRecordSchema().dump(record)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"出库操作失败: {str(e)}"}), 500

@inventory_bp.route('/adjust', methods=['POST'])
@jwt_required()
@admin_required
def adjust_stock():
    """库存调整"""
    data = request.get_json()
    
    product_id = data.get('product_id')
    variant_id = data.get('variant_id')
    quantity = data.get('quantity')  # 正数为增加，负数为减少
    notes = data.get('notes', '')
    
    if not product_id or quantity is None:
        return jsonify({"msg": "请提供有效的商品ID和调整数量"}), 400
    
    try:
        # 更新库存
        if variant_id:
            variant = ProductVariant.query.get(variant_id)
            if not variant:
                return jsonify({"msg": "商品变体不存在"}), 404
            
            if variant.stock + quantity < 0:
                return jsonify({"msg": "调整后库存不能小于0"}), 400
            
            variant.stock += quantity
            product = variant.product
        else:
            product = Product.query.get(product_id)
            if not product:
                return jsonify({"msg": "商品不存在"}), 404
            
            if product.stock + quantity < 0:
                return jsonify({"msg": "调整后库存不能小于0"}), 400
            
            product.stock += quantity
        
        # 创建库存记录
        record_type = InventoryType.IN.value if quantity > 0 else InventoryType.OUT.value
        record = InventoryRecord(
            product_id=product_id,
            variant_id=variant_id,
            type=record_type,
            quantity=abs(quantity),
            notes=notes
        )
        
        db.session.add(record)
        db.session.commit()
        
        return jsonify({
            "msg": "库存调整成功",
            "record": InventoryRecordSchema().dump(record)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"库存调整失败: {str(e)}"}), 500

@inventory_bp.route('/', methods=['GET'])
@jwt_required()
def get_inventory():
    """获取所有库存信息"""
    # 这里需要实现库存查询逻辑
    return jsonify({"message": "库存API - 获取所有库存信息"}), 200 